#!/usr/bin/python3
import logging
from prettytable import PrettyTable
from prettytable import *
from model.ServerConfig import ServerModel

# 菜单类


class MenuTable(object):

    def __init__(self, server_list,menu_config) -> None:
        self.server_list = server_list
        self.menu_config = menu_config
        self.env_list = []
        self.env_len = len(self.env_list)
        self.server_config_list = []
        self.num = 0

    # 展示环境列表

    def showEnvList(self):
        envNum = 1
        # 每次清空列表缓存
        self.env_list.clear()
        for envList in self.server_list:
            env = envList["ENV"]
            print(str(envNum)+":"+env)
            envNum = envNum+1
            self.num=envNum
            # 初始化环境列表缓存
            self.env_list.append(env)

    def getEnvByNum(self, num:int):
        try:
            return self.env_list[num-1]
        except IndexError:
            logging.info("input service config index out of range")
            return self.env_len+1

    def showServerList(self, env:str):
        """
        展示服务器列表
        env: 环境标识文本
        """
        serverNum = 1
        # 每次清空列表缓存
        self.server_config_list.clear()

        for envList in self.server_list:
            if(envList["ENV"] == env):
                # 根据类型获取对应菜单配置
                menu_type = envList["TYPE"]
                m_config = self.menu_config[menu_type]
                # 加载表格配置
                table = self.load_table_confing(menu_type,envList["ENV"])
                # 填充数据到表格
                serviceList = envList["SERVICE_LIST"]
                for service in serviceList:
                    result = []
                    cloumn_name = m_config["column"];
                    for name in cloumn_name:
                        result.append(serverNum if len(result)==0 else service[name])
                    table.add_row(result)
                    
                    sBean = ServerModel().from_config(service,menu_type)
                    # 初始化服务器列表缓存
                    self.server_config_list.append(sBean)
                    serverNum = serverNum+1
                    
                print(table)
        self.num=serverNum-1

    def load_table_confing(self,menu_type,title:str):
        """加载表格配置"""

        m_config = self.menu_config[menu_type]
        global_config = self.menu_config["GLOBAL"]
        table = PrettyTable()
        # 行标题
        table.field_names = m_config["prettytable"]["column"]
        table.set_style(DEFAULT) 
        table.title = title
        table.min_width = global_config["column_wide"]
        return table;